# -*- coding: utf-8 -*-
import datetime
import os
import random
import sys

import qrcode


class GenQRCode(object):

    def __init__(self, root='/data/code/scrapy/demoi/mansite/img/qrcode') -> None:
        super().__init__()
        self.root = root
        self.qr = qrcode.QRCode(version=4,
                                error_correction=qrcode.ERROR_CORRECT_L,
                                box_size=10,
                                border=4)
        # self.colors = ['green', 'red', 'blue', 'pink', 'yellow', 'black', 'gray', 'violet']
        self.colors = ['black']

    def gen_qrcode_img(self, data='http://nanrenvip.site', datas=[]):
        datas.append(data)
        total = len(datas)
        count = 0
        img_path = '/data/code/scrapy/demoi/mansite/img/qrcode'
        for d in datas:
            count += 1
            self.qr.make(fit=True)
            self.qr.add_data(d)
            color = random.choice(self.colors)
            codename = 'CODE{}_{}.jpg'.format(count, datetime.datetime.now().strftime('%Y%m%d%H%M%S%s'))
            print('gen code name: %s' % codename)
            self.qr.make_image(fill_color=color, back_color='white').save(os.path.join(img_path, codename))

            rate = count / total
            used, remain = int(50 * rate), 50 - int(50 * rate)
            progress = '\r[%s%s] %d%%\n' % ('#' * used, ' ' * remain, 100 * rate)
            sys.stdout.write(progress)
            sys.stdout.flush()

        print('Gen QRCode Image Completed, total and path:', total, img_path)

        pass


if __name__ == '__main__':
    gcode = GenQRCode()
    datas = [
        # 'https://app.swag.live/',
        # 'http://dict.youdao.com/',
        # 'https://www.baidu.com/',
        # 'http://nanrenvip.site/olds.html',
        'ctfile://xturlAGMNZ1IyADlQMwU6AmIBbAdmBTNVYgUsBHEBZgdiBzMGMVQyUDRTZlM2DSwEJgxvUjZWZ1VmVG0PPFozAGUBNAA3DW8',
        # 'http://nanrenvip.site/nvyouku/1-0-0-0-0-0-0.html'
    ]
    gcode.gen_qrcode_img(datas=datas)
    exit(0)
